package com.hornsun.client.personalPage.api;

import com.hornsun.client.personalPage.dto.HealthDTO;
import com.hornsun.domain.dbo.HealthIndex;
import com.hornsun.repository.HealthIndexRepository;
import com.hornsun.repository.MedicalRepository;
import com.hornsun.repository.MemberWechatRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by 编译中... on 2018/4/26.
 */
@RestController
@RequestMapping("/api/health")
public class HealthInfoAPI {

    @Resource
    private HealthIndexRepository healthIndexRepository;

    @Resource
    private MedicalRepository medicalRepository;

    @Resource
    private MemberWechatRepository memberWechatRepository;

    @GetMapping("/getHealthInfo")
    public ResponseEntity<HealthDTO> getHealthInfo(HttpServletRequest httpRequest){
        String openid = httpRequest.getAttribute("openid").toString();
        String memberGuid = memberWechatRepository.getMemberGuidByOpenid(openid);
        HealthDTO healthDTO = new HealthDTO();
        healthDTO.setHealthIndexList(healthIndexRepository.getNearHealthIndex(memberGuid));
        healthDTO.setMedicalDTOList(medicalRepository.queryMedicalDTOByGuid(memberGuid));
        return new ResponseEntity<HealthDTO>(healthDTO, HttpStatus.OK);
    }

    @Transactional
    @PostMapping("/updateHealthIndex")
    public ResponseEntity<?> addHealthIndex(HealthIndex healthIndex,HttpServletRequest httpRequest){
        String openid = httpRequest.getAttribute("openid").toString();
        String memberGuid = memberWechatRepository.getMemberGuidByOpenid(openid);
        healthIndex.setMemberGuid(memberGuid);
        healthIndex.setTime(new Date());
        if(healthIndexRepository.checkTodayExist(memberGuid)){
            healthIndexRepository.addHealthIndex(healthIndex);
        }else {
            healthIndexRepository.updateTodayHealthIndex(healthIndex, memberGuid);
        }
        return new ResponseEntity<Object>(HttpStatus.OK);
    }


}
